// SPDX-License-Identifier: GPL-2.0
/*
 * Copyright (C) 2019 Microsoft Corporation.
 *
 * Authors:
 * Prakhar Srivastava <prsriva@linux.microsoft.com>
 */

#include <linux/kexec.h>
#include <linux/of.h>
#ifdef CONFIG_RTOS_HAL_KEXEC_GRAB_IMA_INFO_IN_REBOOT
#include <linux/libfdt.h>
#endif

#ifdef CONFIG_IMA_KEXEC
#ifdef CONFIG_RTOS_HAL_KEXEC_GRAB_IMA_INFO_IN_REBOOT
void arch_ima_clear_kexec_buffer(struct kimage *image)
{
	image->arch.ima_buffer_addr = 0;
	image->arch.ima_buffer_size = 0;
	image->arch.ima_loaded = false;
}

int arch_setup_ima_buffer(struct kimage *image)
{
	int off, ret;
	void *dtb = (void *)image->arch.dtb;

	/* if grab ima buffer faild, we treat this as an error */
	if (!image->arch.ima_loaded) {
		pr_err("grab ima info failed\n");
		return -EINVAL;
	}

	if (!dtb)
		return -EINVAL;
	off = fdt_path_offset(dtb, "/chosen");
	if (off < 0) {
		pr_err("not find chosen node, ret = %d\n", off);
		return -EINVAL;
	}

	ret = setup_ima_buffer(image, dtb, off);
	if (ret) {
		pr_err("setup ima buffer failed, ret = %d\n", ret);
		return ret;
	}

	ret = rebuild_2nd_dtb(dtb, image);
	if (ret) {
		pr_err("build 2nd dtb failed, ret = %d\n", ret);
		return ret;
	}

	return 0;
}
#endif
#endif /* CONFIG_IMA_KEXEC */
